package com.xlh.support.training.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import com.xlh.enums.LocalResourcesEnum;
import com.xlh.exception.common.GlobalException;
import com.xlh.exception.common.NotFoundException;
import com.xlh.service.MdHtmlFileService;
import com.xlh.support.training.dao.TrainingReportMapper;
import com.xlh.support.training.dao.helper.TrainingMapperHelper;
import com.xlh.support.training.dao.helper.TrainingReportMapperHelper;
import com.xlh.support.training.domain.TrainingReport;
import com.xlh.support.training.po.TrainingReportSavePO;
import com.xlh.support.training.service.TrainingReportService;
import com.xlh.support.training.vo.TrainingReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * 实训文件名格式  实训id-用户id
 *
 * @author cheer
 */
@Service
@Slf4j
public class TrainingReportServiceImpl implements TrainingReportService {

    @Autowired
    private MdHtmlFileService mdHtmlFileService;

    @Autowired
    private TrainingReportMapper trainingReportMapper;

    @Autowired
    private TrainingMapperHelper trainingMapperHelper;

    @Autowired
    private TrainingReportMapperHelper trainingReportMapperHelper;

    @Override
    public TrainingReportVO getTrainingReport(Long userId, Long trainingId) {
        String filename = trainingId + "-" + userId;
        try {
            return TrainingReportVO.builder()
                    .conTent(mdHtmlFileService.readFile(LocalResourcesEnum.TRAINING.getLocalUploadPath(),
                            filename + ".md"))
                    .htmlContent(mdHtmlFileService.readFile(LocalResourcesEnum.TRAINING.getLocalUploadPath(),
                            filename + ".html"))
                    .build();
        } catch (NotFoundException e) {
            return TrainingReportVO.builder()
                    .conTent("")
                    .htmlContent("")
                    .build();
        }
    }

    @Override
    public void saveTrainingReport(Long userId, Long trainingId, TrainingReportSavePO trainingReportSavePO) {
        if (trainingMapperHelper.getById(trainingId) == null) {
            throw new GlobalException("实训不存在");
        }

        String filename = trainingId + "-" + userId;
        mdHtmlFileService.writeAllFile(trainingReportSavePO.getContent(), trainingReportSavePO.getHtmlContent(),
                LocalResourcesEnum.TRAINING.getLocalUploadPath(), filename);

        TrainingReport trainingReport = TrainingReport.builder()
                .trainingId(trainingId)
                .userId(userId)
                .build();
        trainingReportMapper.insertSelective(trainingReport);
    }

    @Override
    public void downloadTrainingReport(Long userId, Long trainingId) {
        if (trainingMapperHelper.getById(trainingId) == null) {
            throw new GlobalException("实训不存在");
        }

        String filename = trainingId + "-" + userId;
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try (InputStream inputStream = new FileInputStream(LocalResourcesEnum.TRAINING.getLocalUploadPath(filename + ".html"));
             OutputStream outputStream = response.getOutputStream()) {

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + "实训报告" + ";filename*=UTF-8''" +
                    URLUtil.encode(filename));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        } catch (Exception e) {
            log.error("download training report error", e);
        }
    }

    @Override
    public void deleteTrainingReportByUserIds(List<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return;
        }

        List<TrainingReport> trainingReports = trainingReportMapperHelper.listByUserIds(userIds);
        for (TrainingReport trainingReport : trainingReports) {
            String filename = trainingReport.getTrainingId() + "-" + trainingReport.getUserId();
            FileUtil.del(LocalResourcesEnum.TRAINING.getLocalUploadPath(filename + ".md"));
            FileUtil.del(LocalResourcesEnum.TRAINING.getLocalUploadPath(filename + ".html"));
        }

        trainingReportMapperHelper.deleteByUserIds(userIds);
    }
}
